/* eslint-disable jsdoc/no-restricted-syntax */
/**
 * @param {Record<string, any>} obj
 * @param {string} keyString
 * @param {string=} splitter
 * @returns {any}
 */
export function objectGetDeep(obj, keyString, splitter = ".") {
  const keyArray = keyString.split(splitter);
  if (keyArray.length === 0) {
    throw new Error("keyString is empty");
  } else if (keyArray.length === 1) {
    return Reflect.get(obj, keyArray[0]);
  } else {
    /** @type {*} */
    let preObj;
    let postObj = obj;
    for (let index = 0; index < keyArray.length; index++) {
      preObj = postObj;
      postObj = postObj[keyArray[index]];
      if (!preObj) {
        console.warn(`${keyString}not in${JSON.stringify(obj)}`);
        return;
      }
    }
    return Reflect.get(obj, keyArray[keyArray.length - 1]);
  }
}
// const z = objectGetDeep({ a: { b: { c: { d: 1 } } } }, "a.b.c");
// console.dir(z);

/**
 * @param {Record<string, any>} obj
 * @param {string} keyString
 * @param {any} value
 * @param {string=} splitter
 * @returns {any}
 */
export function objectSetDeep(obj, keyString, value, splitter = ".") {
  const valueArray = keyString.split(splitter);
  if (valueArray.length === 1) {
    return Reflect.set(obj, valueArray[0], value);
  }
  /** @type {*} */
  let preObj;
  let postObj = obj;
  for (let index = 0; index < valueArray.length; index++) {
    preObj = postObj;
    postObj = postObj[valueArray[index]];
    if (!preObj) {
      console.warn(`${keyString}not in${JSON.stringify(obj)}`);
      return false;
    }
  }
  return Reflect.set(preObj, valueArray[valueArray.length - 1], value);
}
// const obj = { a: { b: { c: { d: 1 } } } };
// objectSetDeep(obj, "a.b.c.d", 2);
// console.log(JSON.stringify(obj,));
